<?php

class DbTableEditProcessor {

    const PARAM_TABLE  = 'table';
    const PARAM_DELETE = 'delete';

    private $hAccessors;

    public function __construct() {
        $this->hAccessors = array();
    }

    public function addEditor($name, AbstractTableAccessor $oAccessor) {
        $this->hAccessors[$name] = $oAccessor;
    }

    /**
     * @return AbstractTableAccessor
     */
    private function getCurrentAccessor() {
        return $this->hAccessors[ $this->getCurrentName() ];
    }

    private function getCurrentName() {
        return Form::getPossibleParamAnyway(self::PARAM_TABLE, array_keys($this->hAccessors));
    }

    public function tryDelete() {

        if ($deleteId = Form::getIntAnyway(self::PARAM_DELETE)) {

            $this->getCurrentAccessor()->deleteRecordByKeyField($deleteId);

            $oUrl = Url::createCurrent()->setParams(array(
                self::PARAM_TABLE => $this->getCurrentName(),
            ));

            Output::redirect($oUrl->composeLinkOnSite());
        }
    }

    public function tryDisplay() {

        $currentName = $this->getCurrentName();

        echo "<ul>";
        foreach ($this->hAccessors as $name => $oAccessor) {
            echo ($name == $currentName) ?
                "<li><b>$name</b></li>" :
                "<li><a href='" . $this->composeLink(array(self::PARAM_TABLE => $name)) . "'>$name</a></li>";
        }
        echo "</ul>";

        $this->drawHtmlTable();
    }

    private function drawHtmlTable() {

        $tableAccessor = $this->getCurrentAccessor();
        $arrayOfHashes = $tableAccessor->getRecordsAsHash();
        $keyField = $tableAccessor->getKeyFieldName();

        if (!$arrayOfHashes) return;

        echo '<table border="1">';

        echo '<tr>';
        foreach (array_keys(reset($arrayOfHashes)) as $fieldName) {
            echo "<th>$fieldName</th>";
        }
        echo '<th></th>';
        echo '</tr>';

        $name = $this->getCurrentName();
        foreach ($arrayOfHashes as $key => $hash) {

            echo '<tr>';
            foreach ($hash as $fieldName) {
                if (!$fieldName) $fieldName = '&nbsp;';
                echo "<td>$fieldName</td>";
            }

            $oUrl = Url::createCurrent()->setParams(array(
                self::PARAM_TABLE  => $this->getCurrentName(),
                self::PARAM_DELETE => $hash[$keyField],
            ));

            echo '<td> [<a href="' . $oUrl->composeLinkOnSite() . '" onclick="return confirm(\'Удалить?\')">удалить</a>] </td>';
            echo '</tr>';
        }

        echo '</table>';
    }

    private function composeLink(array $hParams) {
        $result = './?';
        foreach ($hParams as $key => $val) {
            $result .= $key . '=' . $val . '&';
        }
        return $result;
    }
}


?>